<?php


namespace app\impl;


use app\common\lib\HisData;
use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\interfaces\Task;

class SyncOutpatientClinic implements Task
{

    public function run(array $data,string $taskId): ?bool
    {
        $startDate = $data["startDate"] ?? date("Y-m-d", strtotime("-1 day"));
        $endDate = $data["endDate"] ?? date("Y-m-d", strtotime("-1 day"));

        try {
            //$data = HisData::getHisData($data["type"], $startDate, $endDate);
            $data = json_decode(file_get_contents("./menzhen.txt"), true);
            foreach ($data as $k => $v) {
                $v["type"] = 1;
                $v["deleted_at"] = 0;
                $v["created_at"] = time();
                //判断患者是否存在
                $result = ZhyxMongo::getInstance()->setCollection("patient_record")->updateOne(["no" => $v["clinicNo"]], ['$set' => $v], ['upsert' => true]);
                if ($result->getUpsertedId()) {
                    //像患者表中填入记录
                    ZhyxMongo::getInstance()->setCollection("patient_info")->updateOne(["patientId" => $v["patientId"]], ['$push' => [
                        'timeLine' => [
                            'type' => 1,
                            'sex' => $v['patientSex'],
                            'deptName' => $v['deptName'],
                            'no' => $v["clinicNo"],
                            'date' => $v['visitTime'],
                            'dept_id' => $v['deptId'],
                            'doctorName' => $v['attendingDoctorName'] ?? "",
                            'doctorId' => $v['attendingDoctorId'] ?? "",
                            'medicalRecordsNo' => $v['patientNo'],
                            'diagnosis' => $v['diagnosis'] ?: ""
                        ]
                    ]]);

                    //像患者表中填入记录
                    ZhyxMongo::getInstance()->setCollection("patient_info")->updateOne(["patientId" => $v["patientId"]], ['$set' => [
                        'outList' => $v
                    ]]);

                }
            }


        } catch (\Exception $exception) {
            \think\facade\Log::record("同步患者信息异常:" . $exception->getMessage(), "error");
        }

        return true;
    }
}